import * as React from 'react'
import { message, Upload, Button, Icon } from 'antd'
import { serverIP } from '../../service/api'
import Cache from '../../utils/cache'
export interface Props {
  url: string
  fileType: string
  title?: string
  files: any []
  onChange : (param: any) => void
}

export default class HideUpload extends React.Component<Props, {}> {

  beforeUpload = (file: any) => {
    const type = file.type || file.name.split('.')[file.name.split('.').length-1]
    const { fileType } = this.props
    let isJPG=true
    if(fileType)
        isJPG=fileType.indexOf(type)>=0
    if (!isJPG) {
      message.error("请上传"+fileType+"类型文件")
    }
    const isLt2M=true
    return isJPG && isLt2M
  }
  handleChange = (info: any) => {
    const { file: { status, response } } = info
    if (status === 'uploading') {
      this.setState({ loading: true })
      return
    }
    if (status === 'done') {
      message.success(`上传成功`)
      if(this.props.onChange){
        this.props.onChange(response)
      }
    }
    if (status === 'error') {
      message.error(`${info.file.name} 上传失败`)
      this.setState({ loading: false })
    }
  }
  componentWillUnmount () {

  }
  render() {
    const { url, title, files } = this.props
    const props = {
      name: 'file',
      action: serverIP+url,
      headers: {
        token:  Cache.sessionGet('LOGIN_USER').token
      },
      beforeUpload: this.beforeUpload,
      onChange: this.handleChange,
      fileList: files
    }
    return(
      <span>
        <Upload {...props}>
          <Button>
            <Icon type="upload" />{ title || "上传附件" }
          </Button>
        </Upload>
      </span>
    )
  }
}